/*
 * @lc app=leetcode.cn id=92 lang=javascript
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
var reverseBetween = function (head, left, right) {
  if (!head || left === right) return head;

  const dummy = new ListNode(0);
  dummy.next = head;
  let beforeReverseNode = dummy;

  for (let i = 0; i < left - 1; i++) {
    beforeReverseNode = beforeReverseNode.next;
  }

  let cur = beforeReverseNode.next;
  let pre = null;
  const size = right - left + 1;
  for (let i = 0; i < size; i++) {
    const next = cur.next;
    cur.next = pre;
    pre = cur;
    cur = next;
  }
  // console.log(pre.val, pre.next);
  // console.log(cur.val, cur.next);

  beforeReverseNode.next.next = cur;
  beforeReverseNode.next = pre;

  return dummy.next;
};
// @lc code=end
